package cn.edu.mju.user.controller;

import cn.edu.mju.common.entity.pojo.UserInfo;
import cn.edu.mju.common.entity.pojo.VipInfo;
import cn.edu.mju.common.entity.pojo.VipLevel;
import cn.edu.mju.common.entity.result.R;
import cn.edu.mju.common.entity.vo.user.UserVipInfoVO;
import cn.edu.mju.user.service.IUserInfoService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;

/**
 * @author 16423
 */

@RestController
@RequestMapping("/user")
public class UserController {
    private final IUserInfoService iUserInfoService;
    private final MinioClient minioClient;
    @Value("${minio.bucket}")
    private String bucketName;

    @Autowired
    public UserController(MinioClient minioClient, IUserInfoService iUserInfoService) {
        this.minioClient = minioClient;
        this.iUserInfoService = iUserInfoService;
    }

    //TODO 注册
    @PostMapping("/register")
    public R register(@RequestBody UserInfo userInfo){

        boolean flag = iUserInfoService.register(userInfo);

        if (flag) {
            return R.success("注册成功");
        } else {
            return R.error("用户名或邮箱已被绑定");
        }

    }


    //TODO 查询个人信息
    @GetMapping("/getUserInfo")
    public R<UserVipInfoVO> getUserInfo(@RequestParam("userId") String userId) {

        UserInfo userInfo = iUserInfoService.getUserInfo(userId);

        UserVipInfoVO vo = new UserVipInfoVO();

        if (userInfo != null) {
            VipInfo info = VipInfoController.getVipInfoS(userId);

            BeanUtils.copyProperties(userInfo,vo);
            vo.setVipId(info.getVipId());
            vo.setExpTime(info.getExpTime());
            VipLevel level = VipLevelController.getLevelName(info.getLevelId());
            vo.setLevelName(level.getLevelName());
            return R.success(vo);
        } else {
            return R.error("数据错误");
        }

    }


    //TODO 修改密码
    @RequestMapping("/updateUserPwd")
    public R updateUserPwd(@RequestBody UserInfo userInfo) {

        boolean flag = iUserInfoService.updateUserPwd(userInfo);

        if (flag) {
            return R.success("成功");
        } else {
            return R.error("失败");
        }
    }


    //TODO 修改用户头像
    @PostMapping("/uploadAvatar")
    public R<String> uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId) {

        R<String> r = new R<>();
        String originalFilename = file.getOriginalFilename();
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileContentType = file.getContentType().substring(0, file.getContentType().indexOf("/"));
        String avatarName = UUID.randomUUID() + fileType;

        //检查文件类型
        if (!"image".equals(fileContentType)) {
            r.setMsg("非图片类型");
            r.setCode(500);
            return r;
        }

        //检查用户是否存在
        UserInfo checkUser = iUserInfoService.getUserInfo(userId);
        if (checkUser == null) {
            r.setMsg("非法用户");
            r.setCode(500);
            return r;
        }

        try {
            //创建minio连接
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(avatarName)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build();
            //上传至minio
            minioClient.putObject(putObjectArgs);

            //更新用户数据
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(userId);

            String avatarUrl = "http://121.37.211.41:9000/" + bucketName + "/" + avatarName;

            userInfo.setAvatar(avatarUrl);
            boolean flag = iUserInfoService.updateUserInfo(userInfo);
            if (flag) {
                r.setCode(200);
                r.setMsg("上传成功");
                r.setData(avatarUrl);
            } else {
                r.setMsg("非法错误");
                r.setCode(500);
            }
            return r;


        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    //TODO 修改用户数据
    @PostMapping("/updateUserInfo")
    public R updateUserInfo(@RequestBody UserInfo userInfo){

        R r = new R<>();
        boolean flag = iUserInfoService.updateUserInfo(userInfo);
        if (flag){
            r.setCode(200);
            r.setMsg("修改成功");
        }else {
            r.setCode(500);
            r.setMsg("修改失败");
        }
        return r;
    }




    //TODO 查询所有用户信息
    @GetMapping("/getAllUser")
    public R<List<UserInfo>> getAllUser(){
        List<UserInfo> allUser = iUserInfoService.getAllUser();
        return R.success(allUser);

    }
    //TODO 删除用户（逻辑）
    @PostMapping("/logicRemove")
    public R logicRemove(@RequestParam("userId") String userId){
        R  r = new R<>();
        boolean flag = iUserInfoService.logicRemove(userId);
        if (flag){
            r.setCode(200);
            r.setMsg("状态修改成功");
        }else{
            r.setCode(500);
            r.setMsg("失败");
        }
        return r;
    }
    //TODO 删除用户（物理）
    @PostMapping("/physicallyRemove")
    public R physicallyRemove(@RequestParam("userId") String userId){

        R  r = new R<>();
        boolean flag = iUserInfoService.physicallyRemove(userId);
        if (flag){
            r.setCode(200);
            r.setMsg("成功");
        }else{
            r.setCode(500);
            r.setMsg("失败");
        }
        return r;
    }

    //TODO (扩)获取可用空间
    @GetMapping("/getUserSpace")
    public R<Long> getUserSpace(@RequestParam("userId") String userId,@RequestParam("fileSize") Long fileSize ){
        Long userSpace = iUserInfoService.getUserSpace(userId);
        if (userSpace>fileSize){
            return R.success(userSpace);
        }
        return R.error("空间不足");
    }
}
